import React, { useState, useEffect, useRef, useCallback } from "react";
import { Spin, Empty, List, Typography, Checkbox, Button } from "antd";
import ActionFooter from "../ActionFooter"; // 更新导入
import "./style.less";
import { User } from "../../types/user";

const { Text } = Typography;

export interface SearchResultsProps {
  /**
   * 是否显示搜索结果
   */
  visible: boolean;
  /**
   * 是否处于加载状态
   */
  loading: boolean;
  /**
   * 过滤后的选项列表
   */
  options: User[];
  /**
   * 选择选项的回调函数
   */
  onSelect?: (option: User) => void;
  /**
   * 自定义样式
   */
  style?: React.CSSProperties;
  /**
   * 自定义类名
   */
  className?: string;
  /**
   * 最大高度
   */
  maxHeight?: number;
  /**
   * 无结果时的提示文本
   */
  emptyText?: string;
  /**
   * 加载中的提示文本
   */
  loadingText?: string;
  /**
   * 是否支持多选
   */
  multiple?: boolean;
  /**
   * 确认选择的回调函数
   */
  onConfirm?: (selectedOptions: User[]) => void;
  /**
   * 取消选择的回调函数
   */
  onCancel?: () => void;
  /**
   * 已经选择的项目，用于禁用这些项目防止重复选择
   */
  existingSelectedItems?: User[];

  selectedItems?: User[];
  /**
   * 是否启用API分页加载
   */
  usePagination?: boolean;
  /**
   * 当前是否正在加载更多数据
   */
  loadingMore?: boolean;
  /**
   * 是否还有更多数据
   */
  hasMore?: boolean;
  /**
   * 当滚动到底部时触发加载更多
   */
  onLoadMore?: () => void;
  /**
   * 距离底部多少像素时触发加载更多
   */
  threshold?: number;
  /**
   * 加载更多的提示文本
   */
  loadingMoreText?: string;
  /**
   * 无更多数据的提示文本
   */
  noMoreText?: string;
  /**
   * 自定义选项渲染
   */
  renderOption?: (option: User) => React.ReactNode;
}

/**
 * 搜索结果组件
 *
 * 用于显示搜索结果列表，包含加载状态、空结果状态
 */
const SearchResults: React.FC<SearchResultsProps> = ({
  visible,
  loading,
  options,
  onSelect,
  style,
  className = "",
  maxHeight = 300,
  emptyText = "无匹配结果",
  loadingText = "搜索中...",
  multiple = true,
  onConfirm,
  onCancel,
  existingSelectedItems = [],
  selectedItems = [],
  usePagination = false,
  loadingMore = false,
  hasMore = false,
  onLoadMore,
  threshold = 80,
  loadingMoreText = "加载更多...",
  noMoreText = "没有更多数据了",
  renderOption,
}) => {
  // 临时存储选中的对象
  const [tempSelectedItems, setTempSelectedItems] =
    useState<User[]>(selectedItems);

  const contentRef = useRef<HTMLDivElement>(null);
  const scrollTimerRef = useRef<NodeJS.Timeout | null>(null);

  // 检测滚动到底部，触发加载更多
  const handleScroll = useCallback(() => {
    if (scrollTimerRef.current) {
      clearTimeout(scrollTimerRef.current);
    }

    scrollTimerRef.current = setTimeout(() => {
      if (
        contentRef.current &&
        usePagination &&
        !loadingMore &&
        hasMore &&
        onLoadMore
      ) {
        const { scrollTop, scrollHeight, clientHeight } = contentRef.current;
        if (scrollHeight - scrollTop - clientHeight < threshold) {
          onLoadMore();
        }
      }
    }, 100);
  }, [usePagination, loadingMore, hasMore, onLoadMore, threshold]);

  // 滚动事件监听
  useEffect(() => {
    const currentRef = contentRef.current;

    if (visible && currentRef && usePagination) {
      currentRef.addEventListener("scroll", handleScroll);
    }

    return () => {
      if (currentRef) {
        currentRef.removeEventListener("scroll", handleScroll);
      }

      if (scrollTimerRef.current) {
        clearTimeout(scrollTimerRef.current);
      }
    };
  }, [visible, usePagination, handleScroll]);

  if (!visible) return null;

  // 处理复选框变化
  const handleCheckboxChange = (option: User, checked: boolean) => {
    if (checked) {
      setTempSelectedItems((prev) => [...prev, option]);
    } else {
      setTempSelectedItems((prev) =>
        prev.filter((item) => item.id !== option.id)
      );
    }
  };

  // 处理确认按钮点击
  const handleConfirm = () => {
    if (onConfirm) {
      onConfirm(tempSelectedItems as User[]);
    }
  };

  // 处理取消按钮点击
  const handleCancel = () => {
    setTempSelectedItems(existingSelectedItems); // 恢复原始选择
    if (onCancel) {
      onCancel();
    }
  };

  // 计算内容区域最大高度（减去底部按钮高度）
  const contentMaxHeight = multiple ? maxHeight - 50 : maxHeight;

  // 渲染底部加载状态
  const renderFooter = () => {
    if (!usePagination) return null;

    return (
      <div className="results-load-more">
        {loadingMore ? (
          <div className="loading-more">
            <Spin size="small" />
            <span className="loading-text">{loadingMoreText}</span>
          </div>
        ) : hasMore ? (
          <Button
            type="link"
            size="small"
            onClick={onLoadMore}
            className="load-more-btn"
          >
            加载更多
          </Button>
        ) : options.length > 0 ? (
          <div className="no-more-text">{noMoreText}</div>
        ) : null}
      </div>
    );
  };

  // const ceshi = () => {
  //   console.log("ceshi");
  //   console.log("tempSelectedItems", tempSelectedItems);
  //   console.log("existingSelectedItems", existingSelectedItems);
  //   console.log("selectedItems", selectedItems);
  // };
  // 渲染已选中的项目时，不再隐藏它们，而是显示为置灰状态
  return (
    <div
      className={`search-results ${className}`}
      style={{
        marginTop: 4,
        boxShadow: "0 3px 6px rgba(0,0,0,0.1)",
        borderRadius: 4,
        position: "absolute",
        width: "100%",
        zIndex: 100,
        maxHeight: maxHeight,
        overflow: "hidden", // 改为hidden防止内部滚动和外部冲突
        background: "#fff",
        display: "flex",
        flexDirection: "column",
        ...style,
      }}
    >
      <div
        ref={contentRef}
        style={{ overflowY: "auto", maxHeight: contentMaxHeight }}
      >
        {/* <Button onClick={ceshi}>cesh</Button> */}
        {loading && !loadingMore ? (
          <div className="results-loading">
            <Spin size="small" />
            <div className="loading-text">{loadingText}</div>
          </div>
        ) : options.length === 0 ? (
          <div className="results-empty">
            <Empty
              image={Empty.PRESENTED_IMAGE_SIMPLE}
              description={emptyText}
            />
          </div>
        ) : (
          <List
            size="small"
            dataSource={options}
            renderItem={(option: User) => {
              const isAlreadySelected = existingSelectedItems.some(
                (item) => item.id === option.id
              );
              const isTempSelected = tempSelectedItems.some(
                (item) => item.id === option.id
              );

              return (
                <List.Item
                  onClick={() => {
                    if (!multiple && !isAlreadySelected && onSelect) {
                      onSelect(option);
                    }
                  }}
                  className={`result-item ${
                    isAlreadySelected ? "disabled-item" : ""
                  }`}
                  style={{
                    cursor: isAlreadySelected ? "not-allowed" : "pointer",
                    opacity: isAlreadySelected ? 0.5 : 1,
                    backgroundColor: isAlreadySelected ? "#f5f5f5" : undefined,
                  }}
                >
                  {multiple && (
                    <Checkbox
                      checked={isTempSelected}
                      onChange={(e) =>
                        handleCheckboxChange(option, e.target.checked)
                      }
                      onClick={(e) => e.stopPropagation()}
                      style={{ marginRight: 8 }}
                      disabled={isAlreadySelected}
                    />
                  )}
                  {renderOption ? (
                    renderOption(option) // 使用自定义渲染
                  ) : (
                    <List.Item.Meta
                      avatar={option.icon}
                      title={option.name}
                      description={
                        option.description && (
                          <Text type="secondary">{option.description}</Text>
                        )
                      }
                    />
                  )}
                </List.Item>
              );
            }}
          />
        )}

        {/* 分页加载部分 */}
        {renderFooter()}
      </div>

      {multiple && !loading && options.length > 0 && (
        <ActionFooter
          onConfirm={handleConfirm}
          onCancel={handleCancel}
          count={tempSelectedItems.length}
          confirmDisabled={tempSelectedItems.length === 0}
          className="search-results-footer"
        />
      )}
    </div>
  );
};

export default SearchResults;
